import 'dart:async';
import 'dart:isolate';
import 'package:yp_object_mapper/mapper.dart';

class Message extends ObjectMapper {
  int? code;
  int? op;
  int? sop;
  int? opid;
  int? wopid;
  String? sp;
  dynamic data;

  Message({
    this.code,
    this.op,
    this.sop,
    this.opid,
    this.wopid,
    this.sp,
    this.data,
  });

  @override
  Future<void> fromMap(map) async {
    code = map['code'] as int?;
    op = map['op'] as int?;
    sop = map['sop'] as int?;
    opid = map['opid'] as int?;
    wopid = map['wopid'] as int?;
    sp = map['sp'] as String?;
    data = map['data'] as String?;
  }

  @override
  Future toMap() async {
    return {
      if (code != null) 'code': code,
      if (op != null) 'op': op,
      if (sop != null) 'sop': sop,
      if (opid != null) 'opid': opid,
      if (wopid != null) 'wopid': wopid,
      if (sp != null) 'sp': sp,
      if (data != null) 'data': data,
    };
  }
}

void main() async {
  /// 指定转换json时的执行器
  ObjectConverter().executor = <T>(FutureOr<T> Function() action) async {
    return await Isolate.run(action);
  };

  /// 注册对象构建器
  ObjectConverter().quickMapperBuilder(builder: (type) => Message());

  /// 将对象转换为json数据
  Message? encode = Message(
    op: 8,
    sop: 6,
    wopid: 414,
    code: 14,
    sp: "1/scene.query",
    data: "Operation Pending",
  );
  var json = await ObjectConverter().encode(encode);
  assert(json == '{"code":14,"op":8,"sop":6,"wopid":414,"sp":"1/scene.query","data":"Operation Pending"}');

  /// 将json数据转换为对象
  // var decode = await ObjectConverter().decode<Message>(json);
  Message? decode = await ObjectConverter().decode(json);
  assert(decode?.code == 14);
  assert(decode?.op == 8);
  assert(decode?.sop == 6);
  assert(decode?.sp == "1/scene.query");
  assert(decode?.wopid == 414);
  assert(decode?.data == "Operation Pending");
}
